using System;
using System.Collections.Generic;
using System.Text;
using ACompany.OrderProcessing.Model;
using ACompany.OrderProcessing.NHibernateRepository;

namespace ACompany.OrderProcessing.Services
{
    public class CustomerService : ICustomerService
    {
        private readonly ICustomerRepository _customerRepository;

        #region Ctors
        public CustomerService()
            : this(new CustomerRepository())
        {
        }

        public CustomerService(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }
        #endregion

        public void Save(Customer customer)
        {
            if (customer.GetBrokenRules().Count == 0)
            {
                _customerRepository.Save(customer);
            }
            else
            {
                throw new InvalidOperationException(string.Format("the customer cannot be saved in this state {0}", BuildErrorListFrom(customer)));
            }

        }

        private string BuildErrorListFrom(Customer customer)
        {
            var sb = new StringBuilder();
            foreach (var brokenRule in customer.GetBrokenRules())
            {
                sb.AppendLine(brokenRule.Rule);
            }
            return sb.ToString();
        }

        public void Remove(Customer customer)
        {
            if (customer.Orders.Count == 0)
                _customerRepository.Remove(customer);
            else
            {
                throw new ApplicationException("cannot delete a customer that has orders");
            }
        }

        public Customer FindBy(Guid id)
        {
            return _customerRepository.FindBy(id);
        }

        public IList<Customer> FindAll()
        {
            return _customerRepository.FindAll();
        }
    }
}
